package com.atguigu.crowd.mvc.config;

import com.atguigu.crowd.entity.Admin;
import com.atguigu.crowd.entity.Auth;
import com.atguigu.crowd.entity.Role;
import com.atguigu.crowd.service.api.AdminService;
import com.atguigu.crowd.service.api.AuthService;
import com.atguigu.crowd.service.api.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class CrowdUserDetailsService implements UserDetailsService {

    @Autowired
    private AdminService adminService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private AuthService authService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //根据用户名查询当前用户对象
        Admin admin = adminService.getAdminByloginAcct(username);

        Integer adminId = admin.getId();

        //根据adminid查询对应的角色信息
        List<Role> assignRole = roleService.getAssignRole(adminId);

        //根据adminid查询对应的权限信息
        List<String> authNameList=authService.getAssignedAuthNameByAdminId(adminId);

        //创建保存角色和权限信息的list集合
        List<GrantedAuthority> authorities=new ArrayList<>();

        //遍历角色信息保存到authorities集合
        for (Role role:assignRole) {
            //保存的角色信息要拼接前缀
            String roleName="ROLE_"+role.getName();
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(roleName);

            authorities.add(authority);
        }

        //遍历权限信息保存到authorities集合
        for (String authName:authNameList){
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(authName);

            authorities.add(authority);
        }

        //封装SecurityAdmin对象返回
        SecurityAdmin securityAdmin = new SecurityAdmin(admin, authorities);


        return securityAdmin;
    }
}
